package com.doyens.gmall.product.api;

import com.doyens.gmall.common.result.Result;
import io.swagger.annotations.Api;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Classname:TestController
 * PackageName:com.doyens.gmall.product.api
 *
 * @Author:uyijk
 * @Create:2023/7/31 15:26
 * @Version: 1.0
 */
@RestController
@Api(tags = "测试锁")
@RequestMapping("admin/product/test")
public class TestController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping
    public Result testLock(){

        RLock lock = redissonClient.getLock("productTest");

        ValueOperations opsForValue = redisTemplate.opsForValue();
        //查看有没有锁,
        // setIfAbsent：如果redis中没有lock这个key，就添加一个
        String uuid = UUID.randomUUID().toString();
//        Boolean lock = opsForValue.setIfAbsent("lock", uuid,3000, TimeUnit.MILLISECONDS);
        //卡了，不释放锁
        lock.lock();
            String testLock = (String) opsForValue.get("testLock");
            if(testLock==null){
                opsForValue.set("testLock","1");
            }else{
                int num = Integer.parseInt(testLock);
                num++;
                opsForValue.set("testLock",num+"");
            }
            if(opsForValue.get("lock").equals(uuid)) {
                //自己的锁
                //释放锁
                redisTemplate.delete("lock");
            }
        lock.unlock();
        return Result.ok();
    }
}
